<template>
  <section class="wrapper">
    <myHeader :obj="myObj" @events="events"></myHeader>
    <main>
      
      <div class="titles_0314">话题标题（30字以内）</div>
      <div class="text_0314"><label class="label">标题</label><input maxlength="10" placeholder="预设内容" v-model.trim="MessageDetail.Title" type="text"></div>
      <div class="titles_0314">话题描述（20-300字）</div>
      <div class="textarea_0314"><textarea maxlength="300" v-model.trim="MessageDetail.Describe" placeholder="内容描述"></textarea></div>
      <div class="titles_0314">添加图片</div>
      <div class="imgsWrap_0314">
        <span class="imgItem_0314" v-if="MessageDetail.ThumPicUrl" :style="'background-size:cover; background:url('+ MessageDetail.ThumPicUrl + ') no-repeat center center; '"></span>
        <!-- <span class="imgItem_0314" v-for="item in imgArr" :style="{background:'url('+ item + ') no-repeat center center', backgroundSize:'cover'}"></span> -->
        <span class="imgItem_0314 addImg_0314">
          <input type="file" accept="image/gif,image/jpeg,image/jpg,image/png" @change="changeImage($event)" class="uploadImg">
        </span>
      </div>
      <div class="titles_0314 other_0314">适合哪类人群（1-6个）</div>
      <div class="labels_0314">
        <myLabel :closeIcon="true" v-for="(item, index) in labels" :key="index" @removetag="removeLabel(item.RelationshipTallyId, index)">{{item.Tally}}</myLabel>
        <span class="addLabel"  v-if="labels.length < 6" @click="addEles()">添加标签+</span>
      </div>
      <div class="titles_0314 other_0314">约见模式</div>
      <!-- <div class="meetType_0314">
        <span class="meetItem_0314" @click="changeSchema(1)" :class=" MessageDetail.Schema == 1? 'meetActive_0314':''">一对一</span>
        <span class="meetItem_0314" @click="changeSchema(2)" :class=" MessageDetail.Schema == 2? 'meetActive_0314':''">一对多（最多4人）</span>
      </div> -->
      <div class="isTrue" style=""><span>{{isStart?'开启中':'关闭中'}}</span><mt-switch v-model="isStart"></mt-switch><span @click="onOff()" style="display:block; position:absolute; width: .52rem; height: .32rem; right: .15rem;"></span></div>
      <div class="items_0314">
        <label class="itLabels_0314">选择地点</label>
        <input class="itInput_0314" v-model.trim="MessageDetail.Location" type="text">
        <i class="icons2_0314 noIcon2_0316"></i>
      </div>
      <div @click="open('picker1')" class="items_0314">
        <label class="itLabels_0314">约见时间</label>
        <div class="itInput_0314">{{MessageDetail.SeeTime}}</div>
        <i class="icons2_0314"></i>
      </div>
      <div class="items_0314">
        <label class="itLabels_0314">约见金额</label>
        <input class="itInput_0314" type="number" v-model.trim="MessageDetail.Money" placeholder="0">
        <i class="icons2_0314 noIcon2_0316"></i>
      </div>
      <myButton class="marginT_04" @sendDate="clickBtn">提交</myButton>
      
      <!-- 不需要管的html代码 -->
      <mt-datetime-picker  id="add_0314"
        ref="picker1"
        type="date"
        v-model="value1"
        year-format="{value} 年"
        month-format="{value} 月"
        date-format="{value} 日"
        :startDate="startDate"
        :endDate="endDate"
        @confirm="handleChange_1">
      </mt-datetime-picker>
      <mt-datetime-picker id="add_0314_2"
        ref="picker2"
        type="time"
        @confirm="handleChange_2">
      </mt-datetime-picker>
      <mt-datetime-picker id="add_0314_3"
        ref="picker3"
        type="time"
        @confirm="handleChange_3">
      </mt-datetime-picker>
    </main>
    <div id="upProgress" ref="upProgress">
      <div class="pro-in">
        <mt-spinner type="fading-circle" :size="80" color="#454545"></mt-spinner>
        <span class="clarify">上传中... <i id="proPercent">0%</i></span>
      </div>
    </div>
  </section>
</template>
<script>
import myHeader from './base/myHeader';
import myButton from './base/myButton';
import myLabel from './base/myLabel';
import { MessageBox, DatetimePicker, Toast, Spinner } from 'mint-ui';
import Apis from '../assets/js/expertApi';
import hgjSkip from '../assets/js/hgjSkip';
import Client from '../assets/js/common';
import Chat from '../assets/js/chat';
import $ from 'jquery';
export default {
  data () {
    return {
      login:null,
      myObj: { // 头部逐渐
        type: 2,
        text: ''
      },
      existArr: {// 日期组件
        date1: false,
        date2: false,
        date3: false,
      },
      nums: '0%',
      value: null,
      value1: null,
      value2: null,
      startDate: new Date(),
      endDate: new Date('2048-12-31'),
      timeStr: '', // 日期组件
      PMId: true, // 当前页面状态 add 新增页面状态 | update 修改页面状态
      labels: [], // 有id的标签
      isStart: false,
      DelTallyArr: [],
      MessageDetail: { // 新增约见信息
        PostMessageId: this.$route.query.PostMessageId, // 行家信息主表id
        EKind: 0, // 添加的种类 0约见信息 1，知识信息
        Type: 0, // 类型 0.图文（约见必须为图文），1.语音 2.视频
        Title: "", // 标题
        Describe: "", // 描述
        PicUrl: "", // 背景图片链接
        ThumPicUrl: '', // 缩略图链接
        Schema: 1, // 约见模式 约见时必传。 1，一对一 2，一对多
        Money: 0, // 约见金额 约见信息时必须大于0
        SeeTime: '', // 约见时间
        Location: '', // 约见地点
        Tallys: '', // 标签信息，最多6个，多个用,隔开
        State: 0, // 是否开启
      },
      imgArr: [],
      picFile: null, // 文件
    }
  },
  created () {
    hgjSkip.skip().then(res => {
      this.login = res;
    })
    this.PMId = this.$route.query.PostMessageId;
    if(this.PMId) {
      this.myObj.text = "新增话题";
    }else{
      this.myObj.text = "修改话题";
      this.myObj.type = 4;
      this.initUpdateDetails();
      //Toast("更改约见信息")
    }
    
  },
  methods: {
    events(i){
      if(i == 2) {
        history.back();
      }else if(i == 3) {
        this.delete()
      }
    },
    onOff() {
      if(this.MessageDetail.State) {
        this.MessageDetail.State = 0;
      }else{
        this.MessageDetail.State = 1;
      }
    },
    addEles(){
      let eleObj = {};
      eleObj.RelationshipTallyId = null;
      MessageBox.prompt("", {
        message: "添加标签",
        title: "",
        inputPlaceholder: "添加标签(只截取前5字)",
        closeOnClickModal: false // 点击遮罩层不关闭
      }).then(({value, action}) => {
        if(!value) return;
        let val = this.trim(value);
        let len = val.length;
        if(len<=0) return;
        if(len> 5){
          eleObj.Tally = value.slice(0,5);
        }else if(len > 0){
          eleObj.Tally = value
        }
        this.labels.push(eleObj);
      },()=>{

      })

    },
    removeLabel(isId, i) {
      if(isId){
        this.DelTallyArr.push(isId);
      }
      this.labels.splice(i, 1);
    },
    changeStatus(str, status) {
      this.popup[str] = status;
    },
    
    
    clickBtn(){
      //this.MessageDetail.PicUrl = this.imgArr.join(',');
      this.MessageDetail.ThumPicUrl = this.MessageDetail.PicUrl;
      if(this.MessageDetail.Title.length <= 0) return Toast("标题不能为空");
      if(this.MessageDetail.PicUrl.length <= 0) return Toast("图片必须上传");
      if(this.MessageDetail.Location.length <= 0) return Toast("地址不能为空");
      if(this.labels.length <= 0) return Toast("标签最少一个");
      if(!this.MessageDetail.Money || (parseFloat(this.MessageDetail.Money) < 0)) return Toast("金额不能为空或小于零");
      this.addOrUpdateExpertDetail();
    },
    async addOrUpdateExpertDetail() { // 新增或修改接口
      let addArrEle = []
      this.labels.forEach(e => {
        if(e.RelationshipTallyId == null) {
          addArrEle.push(e.Tally)
        }
      })
      if(this.PMId) { // 新增约见信息
        this.MessageDetail.Tallys = addArrEle.join(',');
        await Apis.addExpertDetail({...this.login[1],MessageDetail: this.MessageDetail});
      }else { // 修改约见信息
        this.MessageDetail.AddTally = addArrEle.join(',');
        this.MessageDetail.DelTally = this.DelTallyArr.join(',');
        await Apis.updateExpertDetail({...this.login[1],MessageDetail: this.MessageDetail});
      }
      history.back();
    },
    initUpdateDetails() {
      let currentObj = Client.getStore('MessageDetailItem');
      this.MessageDetail.PostMessageId = currentObj.PostMessageId; // 行家信息主表id
      this.MessageDetail.PostMesssageDetailId = currentObj.EPostMesssageDetailId; // 行家信息明细表id
      this.MessageDetail.EKind = 0; // 添加的种类 0约见信息 1，知识信息
      this.MessageDetail.Type = 0; // 类型 0.图文（约见必须为图文），1.语音 2.视频
      this.MessageDetail.Title = currentObj.Title; // 标题
      this.MessageDetail.Describe = currentObj.Describe; // 描述
      //this.imgArr = currentObj.PicUrl.split(','); // 背景图片链接
      this.MessageDetail.ThumPicUrl = currentObj.ThumPicUrl;  // 缩略图链接
      this.MessageDetail.PicUrl = currentObj.PicUrl;  // 缩略图链接
      this.MessageDetail.Schema = 1;// currentObj.Schema; // 约见模式 约见时必传。 1，一对一 2，一对多
      this.MessageDetail.Money = currentObj.Money; // 约见金额 约见信息时必须大于0
      this.MessageDetail.SeeTime = currentObj.SeeTime; // 约见时间
      this.MessageDetail.Location = currentObj.Location; // 约见地点
      this.labels = currentObj.Tallys; // 标签信息，最多6个，多个用,隔开
      this.MessageDetail.State = currentObj.State;
    },
    delete() {
      Apis.deleteExpertDetail({...this.login[1],'PostMesssageDetailId': this.MessageDetail.PostMesssageDetailId})
      history.back();
    },
    changeSchema(num) {
      this.MessageDetail.Schema = num;
    },
    changeImage(e) {
      let file = e.target.files[0];
      let filesiez = file.size / 1024;
      if(filesiez < 10000){
        // let windowURL = window.URL || window.webkitURL;
        // this.tabContent[this.tabIndex].picView = windowURL.createObjectURL(file);
        // this.$set(this.tabContent, this.tabIndex, this.tabContent[this.tabIndex]);
        this.picFile = e;
        //控制上传进度
        let upProgress = this.$refs.upProgress;
        upProgress.style.display = 'block';
        document.querySelector('#proPercent').innerHTML = '0%';
        Chat.changePicFile(e).then(Res => {
          Toast('图片上传成功');
          this.MessageDetail.PicUrl = Res[0];
          this.MessageDetail.ThumPicUrl = Res[1];
          //this.imgArr.push(Res);
          console.log('上传',Res);
          upProgress.style.display = 'none';
        }).catch(err=>{
          upProgress.style.display = 'none';
          Toast('图片上传失败');
        });
      } else {
        Toast("文件不能大于10M");
      }
      
    },
    trim(str){ 
      return str.replace(/(^\s*)|(\s*$)/g, ""); 
    },
    

    //- 不需要管的代码 --------------------
    //------------------------------------
    //------------------------------------
    addTime(){
      if(!this.existArr.date1){
        let wrap = document.getElementById('add_0314');
        this.base(wrap,'开始时间','date1')
      }
      if(!this.existArr.date2) {
        let wrap2 = document.getElementById('add_0314_2');
        this.base(wrap2,'开始时间','date2')
      }
      if(!this.existArr.date3) {
        let wrap3 = document.getElementById('add_0314_3');
        this.base(wrap3,'结束时间','date3')
      }
    },
    base(wrap, str, status) {
      if(wrap){
        let picker = wrap.getElementsByClassName('picker')[0];
        let newItem = document.createElement("div");
        newItem.setAttribute('class', 'dateTitle_0316');
        newItem.innerHTML = str;
        picker.insertBefore(newItem,picker.childNodes[1]);
        this.existArr[status] = true;
      }
    },
    open(picker) {
      this.$refs[picker].open();
      this.addTime();
    },
    handleChange_1(value) {
      let year = value.getFullYear();
      let month = value.getMonth()+1;
      let day = value.getDate();
      if(month <= 9) {
        month = 0+''+month;
      }
      if(day<=9) {
        day = 0+''+day;
      }
      this.timeStr = year+'-'+month+'-'+day+' ';
      this.open('picker2');
    },
    handleChange_2(value){
      this.timeStr +=value;
      this.open('picker3');
    },
    handleChange_3(value){
      this.timeStr += "-"+value;
      this.MessageDetail.SeeTime = this.timeStr;
    },
    //- 不需要管的代码 --------------------
    //------------------------------------
    //------------------------------------
    
  },
  watch: {
    "MessageDetail.State": function(){
      if(this.MessageDetail.State) {
        this.isStart = true;
      }else {
        this.isStart = false;
      }
    }
  },
  components: {
    myHeader,
    myButton,
    myLabel,
    DatetimePicker
  }
}

</script>

<style lang="less" scoped>
  .wrapper {
    width: 3.75rem;
    height: 100%;
    #upProgress{
      display: none;
      width:100%;
      height:100%;
      position: absolute;
      top:0;
      left:0;
      z-index:9999;
      background: rgba(255,255,255,.9);
      .pro-in{
        height:100%;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        display: flex;
        align-items: center;
      }
      .clarify{
        display: block;
        color:#454545;
        font-size: .14rem;
        padding-top:.16rem;
        i{
          font-size: .18rem;
          font-style: normal;
        }
      }
    }
    main {
      width: 100%;
      height: 100%;
      padding-top: .44rem;
      position: absolute;
      top: 0;
      left: 0;
      overflow-y: auto;
      box-sizing: border-box;
      .isTrue {
        height: .44rem;
        display: flex;
        justify-content:space-between;
        padding: 0 .15rem;
        box-sizing: border-box;
        background-color: white;
        align-items: center;
        position: relative; 
        border-bottom: .01rem solid #E5E5E5;
        span {
          font-size: .17rem;
          font-weight: 500;
          color: #000;
        }
      }
      .dateTitle_0316 {
        height: .3rem;
        line-height: .3rem;
        text-align: center;
        font-size: .16rem;

      }
      .marginT_04 {
        margin: .4rem auto;
      }
      .items_0314 {
        background: white;
        width: 100%;
        height: .44rem;
        padding: 0 .15rem;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: .01rem solid #E5E5E5;
        &:nth-last-of-type(1) {
          border:none;
        }
        .icons2_0314 {
          display: block;
          width: .2rem;
          height: .2rem;
          background: url('../assets/img/icon_shape@3x.png') center center;
          background-size: cover;
          background-repeat: no-repeat;
        }
        .noIcon2_0316 {
           background: none!important;
        }
        .itInput_0314 {
          width: 2.2rem;
          height: .43rem;
          line-height: .43rem;
          color: #B2B2B2;
          font-size: .17rem;
          border: none;
        }
        .itLabels_0314 {
          display: block;
          width: .9rem;
          height: .44rem;
          line-height: .44rem;
          font-size: .17rem;
          font-weight: 500;
          color: #000;
        }
      }
      .meetType_0314 {
        padding: 0 .15rem .35rem;
        overflow: hidden;
        .meetItem_0314 {
          display: block;
          height: .3rem;
          line-height: .3rem;
          padding: 0 .2rem;
          font-size: .14rem;
          background: #828282;
          color: white;
          float: left;
          border-radius: .04rem;
          margin-right: .19rem;
        }
        .meetActive_0314 {
          background: #39393D;
        }
      }
      .labels_0314 {
        overflow: hidden;
        padding: .1rem .2rem 0;
        span {
          display: block;
          height: .3rem;
          line-height: .3rem;
          float: left;
          text-align: center;
          padding: 0 .1rem;
          margin: 0 .14rem .14rem 0;
          border: .04rem;
          border-radius: .04rem;
          font-size: .14rem;
          &.addLabel{
            background: #828282;
            color: white;
          }
        }
        
      }
      .imgsWrap_0314 {
        padding: .15rem .15rem 0 .15rem;
        background: white;
        overflow: hidden;
        .imgItem_0314 {
          background-size: cover !important;
          width: .58rem;
          height: .58rem;
          display: block;
          float: left;
          margin-right: .13rem;
          margin-bottom: .13rem;
          &:nth-of-type(5n) {
            margin-right: 0rem;
          }
        }
        .red {
          background: #ccc!important;
        }
        .addImg_0314 {
          background: url('../assets/img/expert/icon_ba@3x.png') center center;
          background-size: cover;
          background-repeat: no-repeat;
          .uploadImg {
            display: block;
            width: .58rem;
            height: .58rem;
            opacity: 0;
          }
        }
      }
      .textarea_0314 {
        width: 100%;
        padding: .11rem .15rem;
        background: white;
        box-sizing: border-box;
        textarea{
          width: 100%;
          min-height: .53rem;
          font-size: .14rem;
          color: #B2B2B2;
          font-family: "Microsoft YaHei";
        }
      }
      .other_0314 {
        color: #353535!important;
      }
      .titles_0314 {
        width: 100%;
        height: .4rem;
        line-height: .4rem;
        padding-left: .15rem;
        box-sizing: border-box;
        font-size: .14rem;
        color: #888888;

      }
      .text_0314 {
        height: .44rem;
        padding: 0 .15rem;
        background: white;
        display: flex;
        align-items: center;
        .label {
          width: .9rem;
          font-size: .17rem;
          color: #000;
          font-weight: bold;
        }
        input {
          display: flex;
          flex: 1;
          color: #B2B2B2;
          font-size: .17rem;
          border: none;
          line-height: 1;
        }
      }
    }
  }
  
</style>
<style>
  .mint-msgbox .mint-msgbox-input .mint-msgbox-errormsg {
    display: none;
  }
  .mint-msgbox-content .mint-msgbox-message {
    color: #000;
    font-weight: bold;
  }
  .mint-msgbox .mint-msgbox-input input {
    border: .01rem solid #ccc;
    box-sizing: border-box;
    height: .35rem;
    line-height: .35rem;
  }
</style>
